package com.pwc.testing;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.pwc.dataAdaptor.ExcelSheet;
import com.pwc.dataAdaptor.IDataAdaptor;

public class preProcess {

	
	private List<IDataAdaptor> data;
	
	public preProcess(List<IDataAdaptor> data)
	{
		this.data=data;
	}
	
	
	public List<IDataAdaptor> mainPreprocess()
	{
		List<IDataAdaptor> result=new ArrayList<IDataAdaptor>();
		
		for (IDataAdaptor iDataAdaptor : data) {
			
			List<String[]> newTable =new ArrayList<String[]>();
			
			IDataAdaptor newDataAdaptor=new ExcelSheet();
			
			
			for (String[] line : iDataAdaptor.getAllData()) {
				
				List<String> newLineList=new ArrayList<String>();
				
				for(String item : line)
				{
					if(item.contains("{{") )
					{
						//doing process
						item=singleProcess(item);
					}
					
					newLineList.add(item);
				}
				
				
				String[] newLineStrings={};
				
				newLineStrings=newLineList.toArray(newLineStrings);
				
				newTable.add(newLineStrings);
			}
			
			newDataAdaptor.setAllData(newTable);
			newDataAdaptor.setName(iDataAdaptor.getName());
			result.add(newDataAdaptor);
		}
		
		return result;
	}
	
	
	
	private String singleProcess(String item)
	{
		return inputProcess(item);
	}
	
	
	private String inputProcess(String input)
	{
		if(input.contains("{{") )
		{
			int index=input.indexOf("{{")+2;
			int end=input.indexOf("}}");			
			String command= input.substring(index, end);
			int commandIndex=command.indexOf("(");
			int commandEnd=command.indexOf(")");
			String wordString=command.substring(0,commandIndex);
			String number=command.substring(commandIndex+1,commandEnd);
			
			if(wordString.equalsIgnoreCase("random"))
			{
				Random r = new Random();
				int resultNumber= (int)(r.nextDouble()*Double.parseDouble(number)) ;
				input= input.replace("{{"+wordString+"("+number+")}}", String.valueOf(resultNumber));
			}
			
			
		}
		
		return input;
	}
	
	
	
	
}
